


// 提取需要合并的数据
import 'dart:io';
import 'dart:isolate';
import 'package:excel/excel.dart' as top_excel;

extractKeHuInfoData(Map<String, dynamic> extractMap) async {
  SendPort sendPort = extractMap["sendPort"];
  File file = extractMap["data"];
  String sheetName = "Sheet1";
  // 提取之后的数据
  List<Map<String, dynamic>> originDataTemp = [];
  dynamic result = {};
  // 提取每个数据
  top_excel.Excel excel = top_excel.Excel.decodeBytes(file.readAsBytesSync());
  final sheetCms = excel.tables[sheetName];
  if (sheetCms == null) {
    result = {"code": 1, "msg": " 在$file 文件中没有找到$sheetName表，请检查", "data": []};
    sendPort.send(result);
    return;
  }
  // 找到这几个列对应的索引
  // 读取数据，从第二行开始读取数据
  List<List<top_excel.Data?>> rows = sheetCms.rows;
  // 当前表的数量
  var i = file.path.lastIndexOf("\\");
  var fileName = file.path.substring(i, file.path.length);
  sendPort.send({"code": 3, "msg": "正在解析$fileName 文件中$sheetName表，数据数量为${rows.length - 2}"});
  for (var i = 1; i < rows.length; i++) {
    var row = rows[i];
    Map<String, dynamic> valueMap = {};
    for (int i1 = 0; i1 < row.length; i1++) {
      String output = "";
      output = await adjustAddresses(row[i1]?.value.toString() ?? "");
      output = output.replaceAll("\n", "\t").trim().toString();
      if (i1 == 0) {
        valueMap["a"] = output;
      } else if (i1 == 1) {
        valueMap["b"] = output;
      } else if (i1 == 2) {
        valueMap["c"] = output;
      } else if (i1 == 3) {
        valueMap["d"] = output;
      } else if (i1 == 4) {
        valueMap["e"] = output;
      } else if (i1 == 5) {
        valueMap["f"] = output;
      } else if (i1 == 6) {
        valueMap["g"] = output;
      } else if (i1 == 7) {
        valueMap["h"] = output;
      } else if (i1 == 8) {
        valueMap["i"] = output;
      } else if (i1 == 9) {
        valueMap["j"] = output;
      } else if (i1 == 10) {
        valueMap["k"] = output;
      } else if (i1 == 11) {
        valueMap["l"] = output;
      } else if (i1 == 12) {
        valueMap["m"] = output;
      } else if (i1 == 13) {
        valueMap["n"] = output;
      } else if (i1 == 14) {
        valueMap["o"] = output;
      } else if (i1 == 15) {
        valueMap["p"] = output;
      } else if (i1 == 16) {
        valueMap["q"] = output;
      } else if (i1 == 17) {
        valueMap["r"] = output;
      } else if (i1 == 18) {
        valueMap["s"] = output;
      }
    }
    originDataTemp.add(valueMap);
  }

  // 分析数据分类
  List<Map<String, dynamic>> cData = [];
  List<Map<String, dynamic>> nData = [];
  List<Map<String, dynamic>> bData = [];
  for (var element in originDataTemp) {
    if (element["o"] == "127") {
      continue;
    }
    if (element["s"].toString().contains("轉套票")) {
      continue;
    }

    // 群组名称
    var bgNameTemp = element["a"].toString();
    var customerGroup = getGroupName(element["a"], bgNameTemp);
    element["t"] = customerGroup;

    String e = ((element["e"] == "" || element["e"] == null) ? "0" : element["e"]);
    String f = ((element["f"] == "" || element["f"] == null) ? "0" : element["f"]);
    element["u"] = "";
    if (e != "0" && f != "0") {
      element["u"] = (double.parse(e) / double.parse(f)).toStringAsFixed(1);
    }
    if (element["u"] == "NaN") {
      element["u"] = 0;
    }
    element["m"] = element["m"].toString().replaceAll("\n", "").replaceAll("\t", " ").trim();
    element["s"] = element["s"].toString().replaceAll("\n", "").replaceAll("\t", " ").trim();

    element["s"] = element["s"].replaceAll(RegExp(r'\s+'), ' ');

    if (element["s"].toString().contains("客户介绍") || element["s"].toString().contains("客戶介紹")) {
      element["s"] = "客户介绍";
    }

    // 分类
    if (element["l"] == "B" || element["a"].toString().contains("CXCB")) {
      // 宝箱
      bData.add(element);
    } else {
      if (element["l"] == "C") {
        // 套票客
        cData.add(element);
      } else if (element["l"] == "N") {
        // 判断是否有金额和柯打数值
        if (double.parse(element["e"]) == 0 && double.parse(element["f"]) == 0) {
          continue;
        }
        // 非套票客
        nData.add(element);
      }
    }
    print("需要处理的数据： ${element}");
  }
  result = {"code": 0, "msg": "解析成功", "originDataTemp": originDataTemp, "cData": cData, "nData": nData, "bData": bData};
  sendPort.send(result);
}

// 换行的数据调整为1行显示
Future<String> adjustAddresses(String input) {
  List<String> lines = input.split('\n');
  StringBuffer adjustedAddresses = StringBuffer();
  bool inQuotes = false;
  StringBuffer currentAddress = StringBuffer();
  for (String line in lines) {
    line = line.trim();
    if (line.startsWith('"') && !inQuotes) {
      // 开始新的引号部分
      inQuotes = true;
      currentAddress.write(line.substring(1)); // 去掉开头的引号
    } else if (line.endsWith('"') && inQuotes) {
      // 结束引号部分
      inQuotes = false;
      currentAddress.write(' ${line.substring(0, line.length - 1)}'); // 去掉结尾的引号
      adjustedAddresses.writeln(currentAddress.toString().trim()); // 添加整合后的地址
      currentAddress.clear(); // 清空当前地址
    } else if (inQuotes) {
      // 在引号内的行，继续添加
      currentAddress.write(' $line');
    } else {
      // 不在引号内，直接添加
      adjustedAddresses.writeln(line);
    }
  }
  return Future.value(adjustedAddresses.toString());
}

// 返回单个群组名称
String getGroupName(String customerId, String groupName) {
  String? newGroupName;
  if (groupName == "EASY" || groupName == "WINSON" || groupName == "FDC") {
    newGroupName = groupName;
  } else if (customerId == "96571V") {
    newGroupName = "CXC-A組";
  } else if ((customerId == "13192011" && groupName == "CXC EXPRESS") || customerId == "CXC EXPRESS") {
    newGroupName = "CXC-D組";
  } else if (groupName == "ACS") {
    newGroupName = "CXC-信誠";
  } else if (groupName == "CITY") {
    newGroupName = "CXC-城市";
  } else if (groupName == "ASIAN") {
    newGroupName = "亞洲";
  } else if (groupName == "FC") {
    newGroupName = "飞鹏";
  } else if (groupName == "CMS" ||
      groupName == "EDS" ||
      groupName == "JUMBO" ||
      groupName == "PT" ||
      groupName == "CX COURIER" ||
      groupName == "CXC EXPRESS (新)" ||
      groupName == "DDS" ||
      groupName == "FAST DELIVERY") {
    // 判断是否包含字母 ABCD,如果不包含，则认为是CXC-D組
    if(customerId[0] == "A" || customerId[0] == "B" || customerId[0] == "C" || customerId[0] == "D"){
      newGroupName = "CXC-${customerId[0]}組";
    }else{
      newGroupName = "CXC-D組";
    }
  } else if (groupName.contains("CXC")) {
    newGroupName = "CXC-${customerId[0]}組";
  } else if (groupName=="快遞中心有限公司") {
    newGroupName = "CXC-${customerId[0]}組";
  } else {
    newGroupName = groupName;
  }
  return newGroupName;
}

String disGetGroupName(String customerId, String groupName) {
  String? newGroupName;
  if (groupName == "EASY" || groupName == "WINSON" || groupName == "FDC") {
    newGroupName = groupName;
  } else if (customerId == "96571V") {
    newGroupName = "CXC-A組";
  } else if ((customerId == "13192011" && groupName == "CXC EXPRESS") || customerId == "CXC EXPRESS") {
    newGroupName = "CXC-D組";
  } else if (groupName == "ACS") {
    newGroupName = "CXC-信誠";
  } else if (groupName == "CITY") {
    newGroupName = "CXC-城市";
  } else if (groupName == "ASIAN") {
    newGroupName = "亞洲";
  } else if (groupName == "FC") {
    newGroupName = "飞鹏";
  } else if (groupName == "CMS" ||
      groupName == "EDS" ||
      groupName == "JUMBO" ||
      groupName == "PT" ||
      groupName == "CX COURIER" ||
      groupName == "CXC EXPRESS (新)" ||
      groupName == "DDS" ||
      groupName == "FAST DELIVERY") {
    // 判断是否包含字母 ABCD,如果不包含，则认为是CXC-D組
    if(customerId[0] == "A" || customerId[0] == "B" || customerId[0] == "C" || customerId[0] == "D"){
      newGroupName = "CXC-${customerId[0]}組";
    }else{
      newGroupName = "CXC-D組";
    }
  } else if (groupName.contains("CXC")) {
    newGroupName = groupName;
  } else if (groupName=="快遞中心有限公司") {
    newGroupName = "CXC-${customerId[0]}組";
  } else {
    newGroupName = groupName;
  }
  return newGroupName;
}


// 电商数据解析对比
extractDianShangDataContrast(Map<String, dynamic> extractMap) async {
  SendPort sendPort = extractMap["sendPort"];
  List<String> accountCodes = extractMap["accountCodes"];
  File file = extractMap["data"];
  String sheetName = "其他電商比較表";
  // 提取之后的数据
  List<Map<String, dynamic>> originDataTemp = [];
  dynamic result = {};
  // 提取每个数据
  top_excel.Excel excel = top_excel.Excel.decodeBytes(file.readAsBytesSync());
  final sheetCms = excel.tables[sheetName];
  if (sheetCms == null) {
    result = {"code": 1, "msg": " 在$file 文件中没有找到$sheetName表，请检查", "data": []};
    sendPort.send(result);
    return;
  }
  // 找到这几个列对应的索引
  // 读取数据，从第二行开始读取数据
  List<List<top_excel.Data?>> rows = sheetCms.rows;
  // 当前表的数量
  var i = file.path.lastIndexOf("\\");
  var fileName = file.path.substring(i, file.path.length);
  sendPort.send({"code": 3, "msg": "正在解析$fileName 文件中$sheetName表，数据数量为${rows.length - 2}"});
  for (var i = 2; i < rows.length-1; i++) {
    var row = rows[i];
    Map<String, dynamic> valueMap = {};
    for (int i1 = 0; i1 < row.length; i1++) {
      String output = row[i1]?.value.toString() ?? "";
      if (i1 == 0) {
        valueMap["a"] = output;
      } else if (i1 == 1) {
        valueMap["b"] = output;
      } else if (i1 == 2) {
        valueMap["c"] = output;
      } else if (i1 == 3) {
        valueMap["d"] = output;
      } else if (i1 == 4) {
        valueMap["e"] = output;
      } else if (i1 == 5) {
        valueMap["f"] = output;
      } else if (i1 == 6) {
        valueMap["g"] = output;
      }
    }
    originDataTemp.add(valueMap);
  }
  // 分析数据分类
  List<Map<String, dynamic>> existenceData = [];
  List<Map<String, dynamic>> nData = [];
  for (var element in originDataTemp) {

    if(accountCodes.contains(element["a"])){
      existenceData.add(element);
    }else{
      nData.add(element);
    }
    print(element);

  }
  result = {"code": 0, "msg": "解析成功", "existenceData": existenceData, "nData": nData};
  sendPort.send(result);
}